package com.qwc.blog.entity.dto;

import cn.hutool.core.collection.CollUtil;
import com.qwc.blog.common.constant.CommonConstant;
import com.qwc.blog.entity.Classify;
import lombok.Data;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author qiuwencong
 * @Date 2022/2/16 9:53
 * @Package com.qwc.blog.entity.dto
 * @Description
 */
@Data
public class ClassifyTreeDto {
    private Integer value;
    private String label;
    private List<ClassifyTreeDto> children;

    public static List<ClassifyTreeDto> getTree(List<Classify> list, Integer pid,Integer hasRoot) {
        List<ClassifyTreeDto> tree = new ArrayList<>();
        if (CommonConstant.ROOT.equals(hasRoot)) {
            ClassifyTreeDto root = new ClassifyTreeDto();
            root.setValue(CommonConstant.ROOT);
            root.setLabel(CommonConstant.ROOT_DIR);
            addChildren(root, list);
            tree.add(root);
        } else {
            List<ClassifyTreeDto> treeDtoList = list.stream()
                    .filter(classify -> pid.equals(classify.getPid()))
                    .collect(Collectors.toList()).stream().map(classify -> {
                ClassifyTreeDto treeDto = createClassifyTreeDto(classify);
                addChildren(treeDto, list);
                return treeDto;
            }).collect(Collectors.toList());
            tree.addAll(treeDtoList);
        }
        return tree;
    }

    private static void addChildren(ClassifyTreeDto dto, List<Classify> list) {
        for (Classify classify : list) {
            if (classify.getPid().equals(dto.getValue())) {
                if (CollUtil.isEmpty(dto.getChildren())) {
                    dto.setChildren(new ArrayList<>());
                }
                ClassifyTreeDto nextDto = createClassifyTreeDto(classify);
                dto.getChildren().add(nextDto);
                addChildren(nextDto, list);
            }
        }
    }

    private static ClassifyTreeDto createClassifyTreeDto(Classify next) {
        ClassifyTreeDto dto = new ClassifyTreeDto();
        dto.setValue(next.getClassifyId());
        dto.setLabel(next.getName());
        return dto;
    }
}
